package com.me.customerdemo.controller.system;

import com.github.pagehelper.PageInfo;
import com.me.customerdemo.pojo.Role;
import com.me.customerdemo.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/system")
public class RoleController {

    // 初始化一个z在当前类中s使用日志输出
    private static Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    RoleService roleService;

    @GetMapping(value = "/role_add")
    public ModelAndView roleAddView(){
        ModelAndView modelAndView = new ModelAndView("system/role/role_add");
        return modelAndView;
    }

    @GetMapping(value = "/role_list")
    public ModelAndView roleList(
            @RequestParam(name = "pageNum", required = true, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = true, defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) {
        ModelAndView modelAndView = new ModelAndView("system/role/role_list");
        PageInfo<Role> rolePageInfo = roleService.findByKeyword(pageNum, pageSize, keyword);
        modelAndView.addObject("page", rolePageInfo);
        return modelAndView;
    }

    @PostMapping(value = "/role_add")
    public ModelAndView roleAdd(
            @Validated Role role, BindingResult bindingResult
            ){
        ModelAndView modelAndView = new ModelAndView("redirect:/system/role_list?pageNum=1&pageNum=5");
        Map<String, String> errors = new HashMap<>();
        if (bindingResult.hasErrors()){
            // 取出错误对象
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            // 取出发生错误d的字段及相应的c错误信息，放入到映射ji集合中，用于发送到视图环境
            for (FieldError fieldError : fieldErrors) {
                // 从错误对象中取出相应的字段名称为键，对应的错误消息作为值
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            modelAndView.addObject("errors",errors);
            modelAndView.addObject("role",role);
            modelAndView.setViewName("role/role_add");
        }else {
            // 调用服务层方法保存数据
            boolean result = roleService.apply(role);
            if (result) {
                logger.info("管理员***，成功添加了一个新客户 - " + role);
            }else {
                logger.error("管理员***，新增客户信息失败 - " + role);
            }
        }
        return modelAndView;
    }

    @GetMapping("/role_modify")
    public ModelAndView customerModify(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize") int pageSize,
            @RequestParam(name = "pageNum") int pageNum,
            @RequestParam(name = "keyword") String keyword
    ){
        ModelAndView modelAndView = new ModelAndView("system/role/role_modify");
        Role role = roleService.selectById(id);
        modelAndView.addObject("role", role);
        modelAndView.addObject("pageSize", pageSize);
        modelAndView.addObject("pageNum", pageNum);
        modelAndView.addObject("keyword", keyword);
        return modelAndView;
    }

    @PostMapping("/role_modify")
    public ModelAndView customerModify(
            Role role,
            @RequestParam(name = "pageSize",  defaultValue = "5")int pageSize,
            @RequestParam(name = "pageNum",  defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword") String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/system/role_list?pageSize=" + pageSize + "&pageNum=" + pageNum + "&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView modelAndView = new ModelAndView(redirectUrl);
        boolean result = roleService.updataById(role);
              return  modelAndView;
    }

    @GetMapping("/role_remove")
    public ModelAndView customerRemove(
            @RequestParam(name = "id") int id,
            @RequestParam(name = "pageSize",  defaultValue = "5")int pageSize,
            @RequestParam(name = "pageNum",  defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword") String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/system/role_list?pageSize=" + pageSize + "&pageNum=" + pageNum + "&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView modelAndView = new ModelAndView(redirectUrl);
        boolean result = roleService.deleteById(id);
        return modelAndView;
    }
}
